package com.demo.sentinel.command;

import com.alibaba.fastjson.JSONObject;

import javax.script.*;
import java.util.Arrays;
import java.util.List;

public class Demo {
    static ScriptEngineManager manager = new ScriptEngineManager();
    static ScriptEngine js = manager.getEngineByName("js");
    static Bindings en = new SimpleBindings();


    public static void main(String[] args) throws ScriptException {

        String str = "{\n" +
                "\t\"name\": \"张三\",\n" +
                "\t\"sex\": \"男\",\n" +
                "\t\"hobby\": [\n" +
                "\t\t{\n" +
                "\t\t\t\"id\": 1,\n" +
                "\t\t\t\"hobby-name\": \"唱、跳、rap\",\n" +
                "\t\t\t\"hobby-type\": \"艺术\"\n" +
                "\t\t},\n" +
                "\t\t{\n" +
                "\t\t\t\"id\": 2,\n" +
                "\t\t\t\"hobby-name\": \"篮球\",\n" +
                "\t\t\t\"hobby-type\": \"运动\"\n" +
                "\t\t}\n" +
                "\t]\n" +
                "}";

        JSONObject json = JSONObject.parseObject(str);

        en.put("$", json);

        //String cmd = "$.getJSONArray(\"hobby\").getJSONObject(0)";
        String cmd = "$.getJSONArray(\"hobby\").getJSONObject(0).getString(\"hobby-name\")";
        StringBuilder sb = new StringBuilder();
        List<String> list = Arrays.asList(cmd.split("\\."));
        a:
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).contains("-1")) {
                break a;
            } else {
                sb.append(list.get(i)).append(".");
            }
        }
        getJsonResult(sb);
    }

    /**
     * @description:获取解析的json结果
     * @author: hf
     * @date: 2023/2/3 11:47
     * @param: [sb]
     * @return:
     **/
    private static String getJsonResult(StringBuilder sb) throws ScriptException {
        String rst = null;
        if (sb.toString().endsWith(".")) {
            rst = sb.substring(0, sb.length() - 1).concat(";");
        } else {
            rst = sb.substring(0, sb.length()).concat(";");
        }
        System.out.println(rst);
        js.setBindings(en, ScriptContext.ENGINE_SCOPE);
        System.out.println(js.eval(rst));
        return rst;
    }
}